<template>

  <div class="container">
    <div class="card1">
      <div class="title">二维码生成设置</div>
      <div class="lcontainer">
        <!-- <div style="flex:0 0 200px;display: flex;align-items: center;">
          <div style="font-size: 12px;width: 60px;">生成内容</div>
          <textarea placeholder="请输入二维码内容" rows="4" id="qrInfo" v-model="qrInfo"
            style="flex: 1 1 140px;background: #F2F3F5;border: none;font-size: 12px;margin-bottom: 15px;padding: 10px;"></textarea>
          <br />
        </div> -->
        <div style="display: flex;">
          <div style="flex:0 0 200px;display: flex;align-items: center;">
            <div style="font-size: 12px;width: 60px;">版本</div>
            <select v-model="selectedVersion" id="qrVersion"
              style="width: 140px;background: #F2F3F5;border: none;font-size: 12px;height: 28px;">
              <option v-for="num in numbers" :value="num" :key="num">{{ num }}</option>
            </select>
          </div>
          <div style="display: flex;flex:1 1 420px;align-items: center;margin-left: 50px;">
            <MButton style="width: 120px;" @click="generateGrid">重置手绘区域</MButton>
            <MButton style="width: 120px;margin-left: 20px;" @click="contrastResult">结果对比</MButton>

          </div>
        </div>
      </div>
      <div style="margin-top: 30px;">
        <div class="title">二维码手绘</div>
        <div style="display: flex;flex:1 1 420px;align-items: center;margin-top: 20px;">
          <MButton style="width: 120px;" @click="makeCeterCoordinat">生成中心坐标</MButton>
          <MButton style="width: 120px;margin-left: 20px;" @click="showPreview">{{ isShow ? "隐藏" : "显示" }}预览区域</MButton>

        </div>
        <div style="display: flex;margin-top: 20px;">
          <div style="flex: 0 0 230px;display: flex;">
            <div style="width: 80px;text-align: left;">
              中心坐标：
              <div v-for="(c, index) in ceterCoordinate" :key="index" @click="ceterCoordinateClick(index)"
                style="width: 70px;margin: 10px 0;text-align: left;">
                <span :class="'centerCoor' + (selectCoordinate === index ? ' coorSel' : '')"
                  @click="makeOneCoordinat(c)">{{ "(" + c[0] + "，" + c[1] + ")" }}
                </span>
              </div>
            </div>
            <div style="width: 120px;text-align: left;margin-left: 30px;">
              校正图形坐标：
              <div v-for="(c, index) in oneCoordinate" :key="index" style="margin: 10px 0;">{{ "(" + c[0] + "，" + c[1] +
                ")" }}</div>
            </div>
          </div>
          <div style="flex: 1 1 350px;text-align: left;margin-left: 50px;margin-bottom: 20px;" v-if="isShow">
            预览区域：
            <table>
              <tbody>
                <tr>
                  <td></td>
                  <td v-for="(n, rowIndex) in rowNumber" :key="rowIndex">{{ n - 1 }}</td>
                </tr>
                <tr v-for="(row, rowIndex) in tableData1" :key="rowIndex">
                  <td>{{ rowIndex }}</td>
                  <td v-for="(cell, colIndex) in row" :key="`${rowIndex}-${colIndex}`"
                    :style="{ backgroundColor: cell === 1 ? 'black' : 'white', width: '20px', height: '20px' }"></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div style="flex: 1 1 350px;margin-left: 50px;margin-bottom: 20px;text-align: left;" v-if="!isShow">
            手绘区域：
            <table ref="qrTable" style="text-align: center;">
              <tbody>
                <tr>
                  <td></td>
                  <td v-for="(n, rowIndex) in rowNumber" :key="rowIndex">{{ n - 1 }}</td>
                </tr>
                <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
                  <td>{{ rowIndex }}</td>
                  <td v-for="(cell, colIndex) in row" :key="`${rowIndex}-${colIndex}`"
                    :style="{ backgroundColor: cell.color, }" :class="cell.highlight ? 'highlight' : ''"
                    @mouseover="highlightCell(rowIndex, colIndex)" @mouseout="removeHighlight(rowIndex, colIndex)"
                    @click="toggleCellColor(rowIndex, colIndex)"></td>
                </tr>
              </tbody>
            </table>
          </div>

        </div>
      </div>
    </div>

  </div>
</template>

<script>
import MButton from '../components/MButton.vue'
//import MInput from '../components/MInput.vue'
import { ref, onMounted } from 'vue';
export default {
  name: 'QrDestroy',
  props: {
    msg: String
  },
  components: {
    MButton,
    //MInput
  },

  setup() {
    const selectedLevel = ref('0')
    const selectedVersion = ref(2)
    const numbers = ref(Array.from({ length: 10 - 2 + 1 }, (_, i) => i + 2));
    const tableData = ref([]);
    const tableData1 = ref();
    const qrTable = ref(null);
    const qrInfo = ref("5201314")
    const isDraw = ref(false)
    const identifyInfo = ref("")

    const isCenter = ref(false)

    const coordinateInfo = [
      { version: "2", num: "1", coor: [6, 18] },
      { version: "3", num: "1", coor: [6, 22] },
      { version: "4", num: "1", coor: [6, 26] },
      { version: "5", num: "1", coor: [6, 30] },
      { version: "6", num: "1", coor: [6, 34] },
      { version: "7", num: "6", coor: [6, 22, 38] },
      { version: "8", num: "6", coor: [6, 24, 42] },
      { version: "9", num: "6", coor: [6, 26, 46] },
      { version: "10", num: "6", coor: [6, 28, 50] },
      { version: "11", num: "6", coor: [6, 30, 54] },
      { version: "12", num: "6", coor: [6, 32, 58] },
      { version: "13", num: "6", coor: [6, 34, 62] },
      { version: "14", num: "13", coor: [6, 26, 46] },
      { version: "15", num: "13", coor: [6, 26, 48] },
      { version: "16", num: "13", coor: [6, 26, 50] },
      { version: "17", num: "13", coor: [6, 30, 54] },
      { version: "18", num: "13", coor: [6, 30, 56] },
      { version: "19", num: "13", coor: [6, 30, 58] },
      { version: "20", num: "13", coor: [6, 34, 62] }
    ];
    const selectCoordinate = ref(0)
    const ceterCoordinate = ref([])
    const oneCoordinate = ref([])
    const isShow = ref(false)
    const rowNumber = ref(24)
    const contrastResult = () => {
      if (isCenter.value && isDraw.value) {
        var an = []
        for (var a = 0; a < ceterCoordinate.value.length; a++) {
          var nowList = getRectangleCoordinates(ceterCoordinate.value[a][0], ceterCoordinate.value[a][1])
          console.log(ceterCoordinate.value[a], nowList);

          an.push(...nowList)
        }

        var res = 0
        var len = tableData.value.length
        for (let i = 0; i < len; i++) {
          const row = tableData.value[i];
          for (let j = 0; j < row.length; j++) {
            if (row[j].color === "black") {
              res++
              const target = [i, j];
              const isFound = an.some(innerArr => innerArr[0] === target[0] && innerArr[1] === target[1]);
              if (!isFound) {
                alert("结果错误")
                return
              }

            }
          }
        }


        if (res === an.length) {
          alert("结果正确")
          return
        } else {
          alert("结果错误")
          return
        }
      } else {
        alert("请先生成中心坐标")

      }

    }
    const showPreview = () => {
      isShow.value = !isShow.value
      if (isShow.value) {
        var num = Number(selectedVersion.value) * 4 + 17
        const newTableData = [];
        for (let i = 0; i < num; i++) {
          const row = [];
          for (let j = 0; j < num; j++) {
            row.push(0);
          }
          newTableData.push(row);
          tableData1.value = newTableData
        }

      }
    }
    const makeCeterCoordinat = () => {

      const coordinates = coordinateInfo[Number(selectedVersion.value) - 2].coor; // 你提供的数组
      const centerCoordinates = [];

      for (let i = 0; i < coordinates.length; i++) {
        for (let j = 0; j < coordinates.length; j++) {
          const result = isInPositionPattern(coordinates[i], coordinates[j], 4 * Number(selectedVersion.value) + 17);
          if (!result) {
            //centerCoordinates.push("(" + coordinates[i] + "，" + coordinates[j] + ")");
            centerCoordinates.push([coordinates[i], coordinates[j]]);
          }

        }
      }
      ceterCoordinate.value = centerCoordinates
      isCenter.value = true
    }
    function isInPositionPattern(x, y, qrSize) {
      // 假设二维码是 21x21 的大小
      const positionPatterns = [
        { xStart: 0, yStart: 0, xEnd: 7, yEnd: 7 },    // 左上角定位图形
        { xStart: qrSize - 8, yStart: 0, xEnd: qrSize - 1, yEnd: 7 },  // 右上角定位图形
        { xStart: 0, yStart: qrSize - 8, xEnd: 7, yEnd: qrSize - 1 },  // 左下角定位图形
      ];

      // 检查坐标是否在任何一个定位图形区域内
      for (let pattern of positionPatterns) {
        if (x >= pattern.xStart && x <= pattern.xEnd && y >= pattern.yStart && y <= pattern.yEnd) {
          return true;  // 在定位图形区域内
        }
      }

      return false;  // 不在定位图形区域内
    }
    const makeOneCoordinat = (c) => {
      var list = getRectangleCoordinates(c[0], c[1])
      oneCoordinate.value = list

      var num = Number(selectedVersion.value) * 4 + 17
      const newTableData = [];
      for (let i = 0; i < num; i++) {
        const row = [];
        for (let j = 0; j < num; j++) {
          const target = [i, j];
          const isFound = list.some(innerArr => innerArr[0] === target[0] && innerArr[1] === target[1]);
          if (isFound) {
            row.push(1);
          } else {
            row.push(0);
          }

        }
        newTableData.push(row);
      }
      tableData1.value = newTableData

    }

    function getRectangleCoordinates(n, m) {
      const coordinates = [];

      // 上边 (从左到右)
      for (let x = n - 2; x <= n + 2; x++) {
        coordinates.push([x, m - 2]);
      }

      // 右边 (从上到下)
      for (let y = m - 1; y <= m + 2; y++) {
        //coordinates.push({ x: n + 2, y });
        coordinates.push([n + 2, y]);
      }

      // 下边 (从右到左)
      for (let x = n + 1; x >= n - 2; x--) {
        //coordinates.push({ x, y: m + 2 });
        coordinates.push([x, m + 2]);
      }

      // 左边 (从下到上)
      for (let y = m + 1; y > m - 2; y--) {
        //coordinates.push({ x: n - 2, y });
        coordinates.push([n - 2, y]);
      }
      coordinates.push([n, m]);
      return coordinates;
    }
    const ceterCoordinateClick = (index) => {
      selectCoordinate.value = index
    }


    const generateGrid = () => {
      var num = Number(selectedVersion.value) * 4 + 17
      const newTableData = [];
      for (let i = 0; i < num; i++) {
        const row = [];
        for (let j = 0; j < num; j++) {
          row.push({ color: 'white', highlight: false });
        }
        newTableData.push(row);
      }
      isShow.value = false

      tableData.value = newTableData;
      isDraw.value = true
      rowNumber.value = selectedVersion.value * 4 + 17
    };
    // 鼠标悬停时高亮单元格
    const highlightCell = (rowIndex, colIndex) => {
      tableData.value[rowIndex][colIndex].highlight = true;
    };

    // 鼠标移开时移除高亮效果
    const removeHighlight = (rowIndex, colIndex) => {
      tableData.value[rowIndex][colIndex].highlight = false;
    };

    // 点击单元格切换颜色
    const toggleCellColor = (rowIndex, colIndex) => {
      const cell = tableData.value[rowIndex][colIndex];
      cell.color = cell.color === 'white' ? 'black' : 'white';
    };

    onMounted(() => {
      generateGrid()
    });
    return {
      selectedLevel,
      selectedVersion,
      numbers,
      tableData,
      tableData1,
      qrInfo,
      qrTable,
      identifyInfo,
      ceterCoordinate,
      coordinateInfo,
      oneCoordinate,
      selectCoordinate,
      isShow,
      rowNumber,
      contrastResult,
      showPreview,
      makeOneCoordinat,
      makeCeterCoordinat,
      ceterCoordinateClick,
      generateGrid,
      highlightCell,
      removeHighlight,
      toggleCellColor,
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
table {
  margin-top: 10px;
  border-collapse: collapse;
}

/* 表格单元格样式 */
td {
  width: 20px;
  height: 20px;
  border: 1px solid #dadada;
}

.highlight {
  outline: 2px solid orange;
}

#divCanvas {
  border-radius: 5px;
  width: 100%;
  height: 100%;
  /* float: left; */
}

.img {
  width: 25px;
  height: 25px;
  margin: 0 5px;
}

.container_set {
  padding: 5px 20px;
}


.lcontainer {
  padding: 10px;
  margin-top: 20px;
  text-align: left;
}

.title {
  margin-bottom: 10px;
  text-align: left;
}

.container {
  width: 100%;
  min-width: 1700px;
  margin-top: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.card1 {
  width: 90%;
  background: green;
  box-shadow: 0 8px 12px rgba(49, 49, 49, 0.3);
  border-radius: 5px;
  padding: 20px 20px 0 20px;
  background-color: white;
  transition: box-shadow 0.3s ease;

}

.grid {
  display: inline-grid;
  grid-template-columns: repeat(auto-fit, minmax(20px, 1fr));
  gap: 1px;
  margin-top: 20px;
}

.centerCoor {
  border-bottom: 2px solid white;
  cursor: pointer;
}

.centerCoor:hover {
  border-bottom: 2px solid rgb(0, 0, 0);

}

.coorSel {
  border-bottom: 2px solid rgb(0, 0, 0);

}

::-webkit-scrollbar-thumb {
  background-color: #8d8c8c9d
}
</style>
